<template>
  <div>
    <a-tabs style="min-height: 70vh" default-active-key="resource" @change="callback">
      <a-tab-pane key="resource" tab="新建资源">
        <a-form :form="resourceForm" :label-col="{ span: 3 }" :wrapper-col="{ span: 15 }">
          <a-form-item label="资源标题">
            <a-input
                placeholder="请输入资源标题!"
                v-decorator="['resTitle', {
                rules: [{ required: true, message: '请输入资源标题!' }] }]"
            />
          </a-form-item>

          <a-form-item label="资源描述">
            <a-textarea v-decorator="['resDesc', {
                rules: [{ required: true, message: '请输入资源描述!' }] }]"
                        placeholder="请输入资源描述!" :rows="4" />
          </a-form-item>

          <a-form-item label="资源分类">
            <a-select
                v-decorator="[
              'resType',{
                rules: [{ required: true, message: '选择资源分类!' }] },
        ]"
                placeholder="请选择资源分类"
            >
              <a-select-option v-for="item in resourceTypeList || []" :key="item.resourceTypeId" :value="item.resourceTypeId">
                {{item.resourceType}}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="资源文件">
            <div class="clearfix">
              <a-upload
                  :file-list="fileList"
                  :remove="handleRemove"
                  :before-upload="beforeUpload">
                <a-button style="margin-right: 20px" :disabled="fileList.length === 3 || isUpload"> <a-icon type="upload" /> 选择文件 </a-button>
                <span style="color: #cccccc;font-size: 14px">暂时支持: <span v-for="(a,index) in allowType || []" :key="index">{{a}}&nbsp;</span></span>
              </a-upload>
              <a-button
                  type="primary"
                  :disabled="fileList.length === 0"
                  :loading="uploading"
                  style="margin-top: 16px"
                  @click="handleUpload"
              >
                {{ uploading ? '上传中...' : '上传' }}
              </a-button>
            </div>
          </a-form-item>

          <a-form-item label="资源地址">
            <a-input
                placeholder="请输入资源地址!"
                v-decorator="['resUrl', {
                rules: [] }]"
            />
          </a-form-item>

          <a-form-item label="资源标签">
            <div>
              <template v-for="(tag, index) in resTags">
                <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                  <a-tag :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
                    {{ `${tag.slice(0, 20)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag v-else :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
                  {{ tag }}
                </a-tag>
              </template>
              <a-input
                  v-if="inputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="inputValue"
                  @change="handleInputChange"
                  @blur="handleInputConfirm"
                  @keyup.enter="handleInputConfirm"
              />
              <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
                <a-icon type="plus" /> 添加标签
              </a-tag>
            </div>
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
            <a-button type="primary" :disabled="uploading" @click="resHandleSubmit">
              发布
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
<!--      博客-->
      <a-tab-pane key="blog" tab="新建博客" force-render>
        <a-form :form="blogForm" :label-col="{ span: 3 }" :wrapper-col="{ span: 15 }">
          <a-form-item label="博客标题">
            <a-input
                placeholder="请输入博客标题!"
                v-decorator="['blogTitle', {
                rules: [{ required: true, message: '请输入博客标题!' }] }]"
            />
          </a-form-item>

          <a-form-item label="个性标签">
            <div>
              <template v-for="(tag, index) in blogTags || []">
                <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                  <a-tag :key="tag" :closable="index !== 0" @close="() => blogHandleClose(tag)">
                    {{ `${tag.slice(0, 20)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag v-else :key="tag" :closable="index !== 0" @close="() => blogHandleClose(tag)">
                  {{ tag }}
                </a-tag>
              </template>
              <a-input
                  v-if="blogInputVisible"
                  ref="input"
                  type="text"
                  size="small"
                  :style="{ width: '78px' }"
                  :value="inputValue"
                  @change="blogHandleInputChange"
                  @blur="blogHandleInputConfirm"
                  @keyup.enter="blogHandleInputConfirm"
              />
              <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="blogShowInput">
                <a-icon type="plus" /> 添加标签
              </a-tag>
            </div>
          </a-form-item>

          <a-form-item label="博客内容">
            <div style="border: 1px solid #ccc;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 300px; overflow-y: hidden;"
                  v-model="html"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
              />
            </div>
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
            <a-button type="primary" @click="blogHandleSubmit">
              发布
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
<!--      竞技大pk-->
      <a-tab-pane key="pk" tab="新建观点pk">
        <a-form :form="pkForm" :label-col="{ span: 3 }" :wrapper-col="{ span: 15 }">
          <a-form-item label="观点标题">
            <a-input
                placeholder="请输入观点标题!"
                v-decorator="['pkTitle', {
                rules: [{ required: true, message: '请输入博客标题!' }] }]"
            />
          </a-form-item>

          <a-form-item label="观点内容">
            <a-textarea v-decorator="['pkContent', {
                rules: [{ required: true, message: '请输入观点内容!' }] }]"
                        placeholder="请输入观点内容!" :rows="4" />
          </a-form-item>

          <a-form-item label="结束时间">
            <a-date-picker show-time
                           :locale="locale"
                           format="YYYY-MM-DD HH:mm:ss"
                           :disabled-date="disabledDate"
                           :disabled-time="disabledDateTime"
                           v-decorator="['pkEndTime', {
                             rules: [{ required: true, message: '请选择观点结束时间!' }] }]"
                           placeholder="请选择观点结束时间" @change="pkEndTimeChange" @ok="pkOnOk" />
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
            <a-button type="primary" @click="pkHandleSubmit">
              发布
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
  import {FILE_ALLOW_LIST} from "@/constent";
  import {uploadBatch} from "@/api/base";
  import {getTypeList, pushResource} from "@/api/resourse";
  import {addBlog} from "@/api/blog";
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
  import {pushPk} from "@/api/pk";
  import Vue from 'vue'
  import '@wangeditor/editor/dist/css/style.css'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  export default {
    name: "PushResource",
    components: { Editor, Toolbar },
    mounted() {
      this.allowType = FILE_ALLOW_LIST;
      this.loadTypeList();
    },
    data(){
      return {
        // 资源
        resourceForm: this.$form.createForm(this, { name: 'resource' }),
        resourceTypeList:[],
        allowType:[],
        fileList: [],
        uploading: false,
        // 是否已经上传图片
        isUpload:false,
        // 上传成功的图片路径
        resImages:[],
        // 资源-标签
        resTags:[],
        inputVisible: false,
        inputValue: '',

        // 博客
        blogForm: this.$form.createForm(this, { name: 'blog' }),
        blogFileList: [],
        blogUploading: false,
        // 是否已经上传图片
        blogIsUpload:false,
        // 上传成功的图片路径
        blogImages:[],
        // 资源-标签
        blogTags:[],
        blogInputVisible: false,
        blogInputValue: '',
        // 富文本
        editor: null,
        html: '',
        toolbarConfig: { },
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF:{
            uploadImage:{
              server: '/api/base/img/upload',
              fieldName: 'file',
              // 自定义插入图片
              customInsert: (res, insertFn) => {
                // res 即服务端的返回结果
                // 从 res 中找到 url alt href ，然后插图图片
                insertFn(res.data, res.msg, res.data)
              },
            },
            uploadVideo:{
              server: '/api/base/img/upload',
              fieldName: 'file',
              // 自定义插入图片
              customInsert: (res, insertFn) => {
                // res 即服务端的返回结果
                // 从 res 中找到 url alt href ，然后插图图片
                insertFn(res.data, res.msg, res.data)
              },
            }
          }
        },
        mode: 'default', // or 'simple'

        // pk
        pkForm: this.$form.createForm(this, { name: 'pk' }),
        locale:locale,
        currentTime:new Date()
      }
    },
    methods: {
      // 获得资源分类列表
      async loadTypeList(){
        const { code,data,msg } = await getTypeList();
        if (code === 200){
          this.resourceTypeList = data;
        } else {
          console.log(msg);
        }
      },
      // tabs切换回调
      callback(key) {
        console.log(key);
      },
      // 资源添加submit事件
      resHandleSubmit(e){
        e.preventDefault();
        const _this = this;
        this.resourceForm.validateFields((err, values) => {
          if (!err) {
            const {resTags,resImages} = _this;
            let params = {...values, resTagList:resTags, resImages}
            pushResource(params).then(res => {
              const { code,msg } = res;
              if (code === 200){
                _this.$message.success(msg);
                _this.resourceForm.resetFields();
                _this.resTags = [];
                _this.resImages = [];
                _this.isUpload = false;
              }else{
                _this.$message.error(msg);
              }
            })
          }
        });
      },
      //   ------------标签
      // 移除标签
      handleClose(removedTag) {
        const tags = this.resTags.filter(tag => tag !== removedTag);
        this.resTags = tags;
      },
      //
      showInput() {
        this.inputVisible = true;
        this.$nextTick(function() {
          this.$refs.input.focus();
        });
      },
      // 添加标签输入改变
      handleInputChange(e) {
        this.inputValue = e.target.value;
      },
      // 确认添加回车失去焦点事件
      handleInputConfirm() {
        const inputValue = this.inputValue;
        let tags = this.resTags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        Object.assign(this, {
          resTags:tags,
          inputVisible: false,
          inputValue: '',
        });
      },
      // 删除图片
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },
      // 上传之前
      beforeUpload(file) {
        const { type,name,size } = file;
        if (this.fileList && this.fileList.length > 0){
          let flag = false;
          this.fileList.forEach(f => {
            if (f.name === name){
              this.$message.error("不能上传重复文件!");
              flag = true;
            }
          })
          if (flag){
            return true;
          }
        }
        if (size){
          if (size > 11842272){
            this.$message.error("文件大小上限10Mb!");
            return true;
          }
        }
        if (name){
          let postStr = name.substring(name.lastIndexOf('.'));
          if (FILE_ALLOW_LIST.includes(postStr)){
            let flsg = false;
            this.fileList.forEach(f => {
              let post = f.name.substring(name.lastIndexOf('.'));
              if (post === '.mp4' && postStr === '.mp4'){
                this.$message.error("视频文件只能传1个!");
                flsg = true;
                return;
              }
            })
            if (flsg){
              return true;
            }
            this.fileList = [...this.fileList, file];
            return false;
          }
          this.$message.error("文件类型暂不支持!");
          return true;
        }
      },
      // 上传
      async handleUpload() {
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach(file => {
          formData.append('files', file);
        });
        this.uploading = true;

        const {code,data,msg} = await uploadBatch(formData);
        if (code === 200){
          this.fileList = [];
          this.uploading = false;
          this.isUpload = true;
          this.resImages = data;
          this.$message.success(msg);
        } else {
          this.uploading = false;
          this.$message.error(msg);
        }
      },

      // 博客相关
      // 富文本
      onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      },
      blogHandleSubmit(e){
        e.preventDefault();
        const _this = this;
        this.blogForm.validateFields((err, values) => {
          if (!err) {
            const {blogTags,blogImages,html} = _this;
            let params = {...values, blogTagList:blogTags, blogImages, blogContent:html}
            addBlog(params).then(res => {
              const { code,msg } = res;
              if (code === 200){
                _this.$message.success(msg);
                _this.blogForm.resetFields();
                _this.html = '';
                _this.blogTags = [];
                _this.blogImages = [];
                _this.blogIsUpload = false;
              }else{
                _this.$message.error(msg);
              }
            })
          }
        });
      },
      //   ------------标签
      // 移除标签
      blogHandleClose(removedTag) {
        const tags = this.blogTags.filter(tag => tag !== removedTag);
        this.blogTags = tags;
      },
      //
      blogShowInput() {
        this.blogInputVisible = true;
        this.$nextTick(function() {
          this.$refs.input.focus();
        });
      },
      // 添加标签输入改变
      blogHandleInputChange(e) {
        this.blogInputValue = e.target.value;
      },
      // 确认添加回车失去焦点事件
      blogHandleInputConfirm() {
        const inputValue = this.blogInputValue;
        let tags = this.blogTags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        Object.assign(this, {
          blogTags:tags,
          inputVisible: false,
          inputValue: '',
        });
      },
      // 删除图片
      blogHandleRemove(file) {
        const index = this.blogFileList.indexOf(file);
        const newFileList = this.blogFileList.slice();
        newFileList.splice(index, 1);
        this.blogFileList = newFileList;
      },
      // 上传之前
      blogBeforeUpload(file) {
        const { type,name } = file;
        let postStr = name.substring(name.lastIndexOf('.'));
        if (FILE_ALLOW_LIST.includes(postStr)){
          this.blogFileList = [...this.blogFileList, file];
          return false;
        }
        this.$message.error("请上传图片文件");
      },
      // 上传
      async blogHandleUpload() {
        const { blogFileList } = this;
        const formData = new FormData();
        blogFileList.forEach(file => {
          formData.append('files', file);
        });
        this.blogUploading = true;

        const {code,data,msg} = await uploadBatch(formData);
        if (code === 200){
          this.blogFileList = [];
          this.blogUploading = false;
          this.blogIsUpload = true;
          this.blogImages = data;
          this.$message.success(msg);
        } else {
          this.blogUploading = false;
          this.$message.error(msg);
        }
      },

      // pk相关
      pkEndTimeChange(value, dateString) {
        this.currentTime = value;
      },
      pkOnOk(value) {
        console.log('onOk: ', value);
      },

      disabledDate(current) {
        // 日期范围控制
        return current && current < this.$moment().endOf('day');
      },
      // 范围
      range(start, end) {
        const result = [];
        for (let i = start; i <= end; i++) {
          result.push(i);
        }
        return result;
      },
      // 时间限制
      disabledDateTime() {
        return {
          disabledHours: () => this.range(1, 23),
          disabledMinutes: () => this.range(1, 59),
          disabledSeconds: () => this.range(1, 59),
        };
      },
      // pk提交回调
      pkHandleSubmit(e){
        e.preventDefault();
        const _this = this;
        this.pkForm.validateFields((err, values) => {
          if (!err) {
            const {currentTime} = _this;
            let params = {...values, pkEndTime: this.$moment(currentTime).format('yyyy-MM-DD HH:mm:ss')}
            pushPk(params).then(res => {
              const { code,msg } = res;
              if (code === 200){
                _this.$message.success(msg);
                _this.pkForm.resetFields();
              }else{
                _this.$message.error(msg);
              }
            })
          }
        });
      },
    },
    beforeDestroy() {
      const editor = this.editor
      if (editor == null) return
      editor.destroy() // 组件销毁时，及时销毁编辑器
    }
  }
</script>

<style scoped>

</style>
